package game.physics;

import common.Area;
import common.Rectangle;
import common.Vector;

public final class MapCollision {
	public MapCollision(Rectangle obstacle) {
		Obstacle = obstacle;
	}
	
	public final Rectangle Obstacle;
	
	public CollisionSolution solve(SimulationBody body) {
		Rectangle lastBad = body.HitBox.clone();
		lastBad.X += body.Location.X;
		lastBad.Y += body.Location.Y;
		// Trivial rejection
		if(lastBad.overlaps(Obstacle) == false) {
			return null;
		}
		
		Rectangle lastGood = body.HitBox.clone();
		lastGood.X += body.LastLocation.X;
		lastGood.Y += body.LastLocation.Y;
		// Trivial rejection, no solution.
		if(lastGood.overlaps(Obstacle) == true) {
			return new CollisionSolution();
		}
		
		Rectangle hitbox = lastBad.clone();
		Rectangle currentPosition = lastBad.clone();
		
		Vector measure = new Vector(lastGood.X - lastBad.X, lastGood.Y - lastBad.Y);
		float length = measure.length();
		while(length >= 2) {
			// Find the mean position.
			hitbox.X = (lastGood.X + lastBad.X) / 2;
			hitbox.Y = (lastGood.Y + lastBad.Y) / 2;
			// Test by moving the boxes ever closer to the collision point.
			if(hitbox.overlaps(Obstacle) == true) {
				hitbox.copyTo(lastBad);
			} else {
				hitbox.copyTo(lastGood);
			}
			length = length / 2;
		}
		
		return new CollisionSolution(currentPosition, lastGood, Obstacle);
	}
}